package com.yixq.soa.service.comm.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpUtils {

	private static Logger log = LoggerFactory.getLogger(HttpUtils.class);

	private static PoolingHttpClientConnectionManager connMgr;
	private static RequestConfig requestConfig;
	private static final int MAX_TIMEOUT = 30000;

	static {
		// 设置连接池
		connMgr = new PoolingHttpClientConnectionManager();
		// 设置连接池大小
		connMgr.setMaxTotal(100);
		connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

		RequestConfig.Builder configBuilder = RequestConfig.custom();
		// 设置连接超时
		configBuilder.setConnectTimeout(MAX_TIMEOUT);
		// 设置读取超时
		configBuilder.setSocketTimeout(MAX_TIMEOUT);
		// 设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
		// 在提交请求之前 测试连接是否可用
		// configBuilder.setStaleConnectionCheckEnabled(true);
		connMgr.setValidateAfterInactivity(5000);

		requestConfig = configBuilder.build();
	}

	public static Optional<JSONObject> postJSON(String url, Map<String, Object> params, String body) {
		
		Optional<String> http = post(url, params, body);
		if (http.isPresent()) {
			try {
				JSONObject obj = JSON.parseObject(http.get());
				return Optional.of(obj);
			} catch (Exception ex) {
				log.error("ERROR GET:" + url);
				log.error("result:" + http.get());
				log.error(ex.getMessage(), ex);
			}
		}

		return Optional.empty();
	}

	public static Optional<String> post(String url, Map<String, Object> params, String body) {
		log.debug("【【【  Start POST:"+url);
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connMgr)
				.setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = null;
		String str = null;
		CloseableHttpResponse response = null;

		try {
			String apiUrl = url;
			OutputStream os = null;
			if (params != null && !params.isEmpty()) {
				List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
				for (Map.Entry<String, Object> param : params.entrySet()) {
					BasicNameValuePair nvp = new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue()));
					nvps.add(nvp);
				}
				UrlEncodedFormEntity ufe = new UrlEncodedFormEntity(nvps, Charset.forName("utf-8"));
				os = new ByteArrayOutputStream();
				ufe.writeTo(os);
				String endPath = os.toString();
				apiUrl = apiUrl + "?" + endPath;
			}

			httpPost = new HttpPost(apiUrl);
			httpPost.setHeaders(null);
			httpPost.setConfig(requestConfig);

			if (StringUtils.isNotBlank(body)) {
				StringEntity entity = new StringEntity(body, Charset.forName("utf-8"));
				httpPost.setEntity(entity);
			}

			// TODO 支持参数和 post body
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();

			HttpEntity entity = response.getEntity();

			if (entity != null) {
				str = EntityUtils.toString(entity, "utf-8");
			}
			
			if (statusCode != HttpStatus.SC_OK) {
				if (entity != null) {
					log.warn(str);
				}
			}

			return Optional.ofNullable(str);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}

		return Optional.empty();
	}
	
	/**
	 * POST一个JSON字符串
	 * @param url
	 * @param param
	 * @return
	 */
	public static Optional<String> postJson(String url, Object param) {
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connMgr)
				.setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = null;
		String str = null;
		CloseableHttpResponse response = null;

		try {
			String apiUrl = url;

			httpPost = new HttpPost(apiUrl);
			httpPost.setHeaders(null);
			httpPost.setConfig(requestConfig);

			if (param != null) {
				StringEntity entity = new StringEntity(JSON.toJSONString(param), Charset.forName("utf-8"));
				entity.setContentType("application/json");
				httpPost.setEntity(entity);
			}

			// TODO 支持参数和 post body
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();

			HttpEntity entity = response.getEntity();

			if (entity != null) {
				str = EntityUtils.toString(entity, "utf-8");
			}
			
			if (statusCode != HttpStatus.SC_OK) {
				if (entity != null) {
					log.warn(str);
				}
			}

			return Optional.ofNullable(str);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}

		return Optional.empty();
	}

	public static Optional<JSONObject> getJSON(String url) {
		Optional<String> http = get(url);
		if (http.isPresent()) {
			try {
				JSONObject obj = JSON.parseObject(http.get());
				return Optional.of(obj);
			} catch (Exception ex) {
				log.error("ERROR GET:" + url);
				log.error("result:" + http.get());
				log.error(ex.getMessage(), ex);
			}
		}

		return Optional.empty();
	}

	public static Optional<String> get(String url) {
		log.debug("【【【 Start GET:"+url);
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connMgr)
				.setDefaultRequestConfig(requestConfig).build();
		HttpGet httpGet = new HttpGet(url);
		String str = null;
		CloseableHttpResponse response = null;

		httpGet.setConfig(requestConfig);
		try {
			response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			str = EntityUtils.toString(entity, "utf-8");
			log.info("http get response ---> {}", str);
			if (statusCode == HttpStatus.SC_OK) {
				return Optional.of(str);
			}

		} catch (IOException e) {
			log.error(e.getMessage(), e);
			e.printStackTrace();
		}

		return Optional.empty();
	}

	/**
	 * sslPost
	 * 
	 * @param apiUrl
	 *            url地址，必须是?以前的部分
	 * @param params
	 *            form形式的参数
	 * @param body
	 *            body形式的传参
	 * @return 返回responseBody串
	 */
	public static Optional<String> sslPost(String apiUrl, Map<String, Object> params, String body) {
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		String result = null;

		try {
			String endPath = createKvParams(params);
			if (StringUtils.isNotBlank(endPath)) {
				apiUrl = apiUrl + "?" + endPath;
			}
			httpPost = new HttpPost(apiUrl);
			httpPost.setHeaders(null);
			httpPost.setConfig(requestConfig);

			if (StringUtils.isNotBlank(body)) {
				StringEntity entity = new StringEntity(body, Charset.forName("utf-8"));
				httpPost.setEntity(entity);
			}

			response = httpClient.execute(httpPost);

			HttpEntity responseEntity = response.getEntity();
			if (responseEntity == null) {
				return Optional.empty();
			}
			result = EntityUtils.toString(responseEntity, Charset.forName("utf-8"));
			
			log.info("sslPost response --> {}", result);
			
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return Optional.empty();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Optional.of(result);
	}

	/**
	 * sslPost
	 * 
	 * @param apiUrl
	 *            url地址，必须是?以前的部分
	 * @param headers
	 *            Header
	 * @param params
	 *            form形式的参数
	 * @param body
	 *            body形式的传参
	 * @return 返回responseBody串
	 */
	public static Optional<String> sslPost(String apiUrl, Header[] headers, Map<String, Object> params, String body) {
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		String result = null;

		try {
			String endPath = createKvParams(params);
			if (StringUtils.isNotBlank(endPath)) {
				apiUrl = apiUrl + "?" + endPath;
			}
			httpPost = new HttpPost(apiUrl);
			if (headers != null && headers.length > 0) {
				httpPost.setHeaders(headers);
			}
			httpPost.setConfig(requestConfig);

			if (StringUtils.isNotBlank(body)) {
				StringEntity entity = new StringEntity(body, Charset.forName("utf-8"));
				httpPost.setEntity(entity);
			}

			response = httpClient.execute(httpPost);
			
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity == null) {
				return Optional.empty();
			}
			result = EntityUtils.toString(responseEntity, Charset.forName("utf-8"));

			log.info("sslPost response --> {}", result);
			
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return Optional.empty();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Optional.of(result);
	}

	/**
	 * sslDelete
	 * 
	 * @param apiUrl
	 *            url地址，必须是?以前的部分
	 * @param headers
	 *            Header
	 * @param params
	 *            form形式的参数
	 * @return 返回responseBody串
	 */
	public static Optional<String> sslDelete(String apiUrl, Header[] headers, Map<String, Object> params) {
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpDelete httpDelete = null;
		CloseableHttpResponse response = null;
		String result = null;

		try {
			String endPath = createKvParams(params);
			if (StringUtils.isNotBlank(endPath)) {
				apiUrl = apiUrl + "?" + endPath;
			}
			httpDelete = new HttpDelete(apiUrl);
			if (headers != null && headers.length > 0) {
				httpDelete.setHeaders(headers);
			}
			httpDelete.setConfig(requestConfig);

			response = httpClient.execute(httpDelete);
			
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity == null) {
				return Optional.empty();
			}
			result = EntityUtils.toString(responseEntity, Charset.forName("utf-8"));
			
			log.info("sslPost response --> {}", result);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return Optional.empty();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Optional.of(result);
	}

	public static Optional<String> sslPost(String apiUrl, Map<String, Object> params) {
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();

		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
			}

			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return Optional.empty();
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return Optional.empty();
			}
			httpStr = EntityUtils.toString(entity, "utf-8");

			return Optional.of(httpStr);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return Optional.empty();
	}

	public static Optional<String> sslPostXml(String apiUrl, String xml) {
		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();

		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(new StringEntity(xml, Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return Optional.empty();
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return Optional.empty();
			}
			httpStr = EntityUtils.toString(entity, "utf-8");

			return Optional.of(httpStr);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return Optional.empty();
	}

	/**
	 * 创建SSL安全连接
	 * 
	 * @return
	 */
	private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
		SSLConnectionSocketFactory sslsf = null;
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

				@Override
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}

			}).build();
			sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {

				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			});
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
		return sslsf;
	}
	
	/**
	 * 创建KV形式的参数(utf-8编码)
	 * @param params
	 * @return a=b&c=d
	 */
	public static String createKvParams(Map<String, Object> params) {
		ByteArrayOutputStream os = null;
		String kvParams = null;
		try {
			if (params != null && !params.isEmpty()) {
				List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
				for (Map.Entry<String, Object> param : params.entrySet()) {
					BasicNameValuePair nvp = new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue()));
					nvps.add(nvp);
				}
				UrlEncodedFormEntity ufe = new UrlEncodedFormEntity(nvps, Charset.forName("utf-8"));
				os = new ByteArrayOutputStream();

				ufe.writeTo(os);
				kvParams = os.toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return kvParams;
	}
	public static void main(String[] args) {
		Map<String, Object> params = new HashMap<>();
		params.put("appid", 1234L);
		params.put("age", 10);
		params.put("money", 1.001D);
		params.put("secret", "AFDXD");
		params.put("cn", "中国");
		String kvParams = createKvParams(params);
		System.out.println(kvParams);
	}
}
